//
//  JKFileExplorerPlistReader.m
//  Baisi
//
//  Created by albert on 2018/11/30.
//  Copyright © 2018 安永博. All rights reserved.
//

#import "JKFileExplorerPlistReader.h"

@implementation JKFileExplorerPlistReader

+ (void)readPlistWithFilePath:(NSString *)filePath complete:(void(^)(NSString *result))complete{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        id plist = nil;
        
        plist = [NSDictionary dictionaryWithContentsOfFile:filePath];
        
        if (!plist) {
            
            plist = [NSArray arrayWithContentsOfFile:filePath];
        }
        
        if (!plist) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                !complete ? : complete(nil);
            });
            
            return;
        }
        
        if (![NSJSONSerialization isValidJSONObject:plist]) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                !complete ? : complete(nil);
            });
            
            return;
        }
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:plist options:NSJSONWritingPrettyPrinted error:nil];
        
        if (!jsonData) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                !complete ? : complete(nil);
            });
            
            return;
        }
        
        NSString *jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                !complete ? : complete(jsonString);
            });
        });
    });
}
@end
